﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using DayDayUp.Core;
using DayDayUp.Core.Data;
using DayDayUp.Core.Domain.Users;
using DayDayUp.Service.Securitys;
using DMS.Core;

//using Dms.Fund;

namespace DayDayUp.Service.Users
{
    public class UserService : IUserService
    {
        private IMongoRepository<UserRole> _userRoleRepository;
        private IMongoRepository<User> _userRepository;
        private IEncryptionService _encryptionService;

        public UserService(IMongoRepository<UserRole> userRoleRepository, IMongoRepository<User> userRepository, IEncryptionService encryptionService)
        {
            _userRoleRepository = userRoleRepository;
            _userRepository = userRepository;
            _encryptionService = encryptionService;
        }

        public User InsertGuestUser()
        {
            var customer = new User()
            {
                UserGuid = Guid.NewGuid(),
                Active = true,
                CreateOn = DateTime.Now,
            };

            //add to 'Guests' role
            var guestRole = GetUserRoleBySystemName(SystemUserRoleNames.Guests);
            if (guestRole == null)
                throw new Exception("'Guests' role could not be loaded");
            customer.UserRoles = new Collection<UserRole>();
            customer.UserRoles.Add(guestRole);

            _userRepository.Insert(customer);

            return customer;
        }

        public User GetUserById(string customerId)
        {
            var query = from c in _userRepository.Table()
                        where c.Id == customerId
                        select c;
            var customer = query.FirstOrDefault();
            if (customer != null)
            {

                return customer;
            }
            else
            {
                return null;
            }
        }

        public User GetUserByUserName(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName))
                return null;

            var query = from c in _userRepository.Table()
                        where c.Name == userName
                        select c;
            var user = query.FirstOrDefault();
            if (user != null)
            {

                return user;
            }
            else
            {
                return null;
            }
        }

        UserRole IUserService.GetUserRoleBySystemName(string rolename)
        {

            return GetUserRoleBySystemName(rolename);

        }

       

       

        //private void UpdateMerchantInfo(int merchantId)
        //{
        //    var merchant = _merchantRep.GetById(merchantId);
        //    if (merchant != null)
        //    {
        //        merchant.TradingPassword = string.Empty;
        //        merchant.ContactName = string.Empty;
        //        _merchantRep.Update(merchant);
        //    }

        //}

        public void CreateUser(string userName, string email, string password, IList<string> roles)
        {
            if (String.IsNullOrEmpty(email))
            {
                throw new Exception("email  is empty");
            }

            if (!CommonHelper.IsValidEmail(email))
            {
                throw new Exception("email wrong format");
            }

            if (String.IsNullOrWhiteSpace(password))
            {
                throw new Exception("password is empty");

            }

            if (String.IsNullOrWhiteSpace(userName))
            {
                throw new Exception("username is empty");

            }
            //validate unique user
            if (GetUserByEmail(email) != null)
            {
                throw new Exception("Email Already Exists");
            }

            if (GetUserByUserName(userName) != null)
            {
                throw new Exception("Username Already Exists");
            }
            var customer = new User()
            {
                Active = true,
                Name= userName,
                Password = _encryptionService.CreatePasswordHash(password, ConstInfo.PasswordSalt, ConstInfo.PasswordFormat),
                Email = email,
                UserGuid = Guid.NewGuid(),
                Deleted = false,
                CreateOn = DateTime.Now
            };


            customer.UserRoles = new Collection<UserRole>();
            foreach (var roleId in roles)
            {

                var userRole = _userRoleRepository.Table().Where(c => c.Id == roleId).SingleOrDefault();
                customer.UserRoles.Add(userRole);
            }

            if (!customer.UserRoles.Any(c => c.SystemName == SystemUserRoleNames.Registered))
            {
                var registed = _userRoleRepository.Table().Where(c => c.SystemName == SystemUserRoleNames.Registered).SingleOrDefault();
                customer.UserRoles.Add(registed);
            }

            _userRepository.Insert(customer);

        }


        private UserRole GetUserRoleBySystemName(string rolename)
        {
            var query = from cr in _userRoleRepository.Table()
                        where cr.SystemName == rolename
                        select cr;
            var customerRole = query.FirstOrDefault();
            return customerRole;
        }



        public User GetUserByEmail(string emailorUserName)
        {
            if (string.IsNullOrWhiteSpace(emailorUserName))
                return null;

            List<User> customers = null;
            if (emailorUserName.Contains("@"))
            {
                var query = from c in _userRepository.Table()
                            where c.Email == emailorUserName
                            select c;
                var customer = query.SingleOrDefault();
                return customer;
            }
            else
            {
                var query = from c in _userRepository.Table()
                            where c.Name== emailorUserName
                            select c;
                var customer = query.SingleOrDefault();
                return customer;
            }

            //if (customers != null && customers.Count > 0)
            //{

            //    var customer = customers[0];
            //    return customer;
            //}
            //else
            //{
            //    return null;
            //}


        }

        public User GetUserByGuid(Guid customerGuid)
        {
            var query = from c in _userRepository.Table()
                        where c.UserGuid == customerGuid
                        select c;
            var customer = query.FirstOrDefault();
            if (customer != null)
            {

                return customer;
            }
            else
            {
                return null;
            }
        }
    }
}